<template>
  <div class="app-container">

    <el-breadcrumb>
      <el-breadcrumb-item :to="{path:'/index'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <el-form :inline="true" ref="queryForm" :model="query">
      <el-form-item label="角色名称" prop="name">
        <el-input clearable v-model="query.name" size="small" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain @click="showDialog(undefined)">新增</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"/>
      <el-table-column label="序号">
        <template #default="scope">{{ (query.currentPage - 1) * (query.pageSize) + scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="name" label="角色名称"></el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="showDialog(scope.row)">修改</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
            <el-button style="margin:0 8px" slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        background
        :page-size="query.pageSize"
        :total="total"
        :current-page.sync="query.currentPage"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @closed="handleClose" append-to-body>
      <el-form ref="saveOrUpdateForm" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="权限菜单" prop="menuIds">
          <el-tree
              ref="menuTree"
              :data="menuList"
              show-checkbox
              :check-on-click-node="true"
              :expand-on-click-node="false"
              node-key="id"
              :default-expanded-keys="[1,2]"
              :default-checked-keys="form.menuIds"
              :props="{label: 'name'}">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/http/request";
import qs from "qs";

export default {
  data() {
    return {
      // 查询参数
      query: {
        currentPage: 1,
        pageSize: 5,
        name: undefined
      },
      // 总记录数
      total: 1,
      // 表格数据
      tableData: [],
      // 选择的ids
      selectedIds: [],
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {
        id: undefined,
        name: undefined,
        menuIds: []
      },
      // 验证规则
      rules: {
        name: [{required: true, message: '名称不能为空', trigger: 'blur'}]
      },
      // 菜单列表
      menuList: [{"id": 1, "name": "商城管理", "children": [{"id": 4, "name": "类别管理"}]},
        {"id": 2, "name": "系统管理", "children": [{"id": 5, "name": "用户管理"}]},
        {"id": 3, "name": "会员管理"}]
    };
  },
  methods: {
    listData() {
      // TODO 发送异步请求处理 ...
      /*request({
        url: '/api/sys/role/list',
        method: 'get',
        params: this.query
      }).then(res => {
        this.total = res.data.total;
        this.tableData = res.data.list;
      });*/
      // 以下是模拟服务端响应的用户分页对象
      this.total = 22
      this.tableData = [{
        "id": 1,
        "name": "管理",
        "menuIds": [2, 5]
      }, {
        "id": 2,
        "name": "运营",
        "menuIds": [1, 4]
      }, {
        "id": 3,
        "name": "普通",
        "menuIds": [3]
      }]
      window.scrollTo(0, 0)
    },
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
      console.log(this.selectedIds)
    },
    handleQuery() {
      this.query.currentPage = 1
      this.listData()
    },
    resetQuery() {
      this.$refs['queryForm'].resetFields()
      this.handleQuery()
    },
    handleCurrentChange(val) {
      this.query.currentPage = val
      this.listData()
    },
    handleSizeChange(val) {
      this.query.pageSize = val
      this.listData()
    },
    handleDelete(row) {
      request({
        url: `/api/sys/role/${row.id}/delete`,
        method: 'post'
      }).then(res => {
        this.$message.success('删除成功')
        this.listData();
      });
    },
    showDialog(row) {
      if (row) {
        this.dialogTitle = '修改角色'
        // TODO 查询要修改的数据回显 ...
        /*request({
          url: `/api/sys/role/${row.id}`,
          method: 'get'
        }).then(res => {
          this.form = res.data;
        });*/
        // 模拟查询服务器响应的数据
        this.form = JSON.parse(JSON.stringify(row))
        this.dialogVisible = true
      } else {
        this.dialogTitle = '新增角色'
        this.dialogVisible = true
      }
    },
    saveOrUpdate() {
      this.$refs['saveOrUpdateForm'].validate(valid => {
        if (!valid) {
          this.$message.error('请正确填写参数')
          return false
        }
        const checkedKeys = this.$refs['menuTree'].getCheckedKeys();
        console.log(checkedKeys)
        if (checkedKeys.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择菜单权限'
          })
          return false
        }
        this.form.menuIds = checkedKeys
        console.log(this.form)
        if (this.form.id) {
          // 修改操作
          request({
            url: '/api/sys/role/update',
            method: 'post',
            data: qs.stringify(this.form)
          }).then(res => {
            this.$message.success('修改成功')
            this.handleClose()
            this.listData()
          })
        } else {
          // 新增操作
          request({
            url: '/api/sys/role/addnew',
            method: 'post',
            data: qs.stringify(this.form)
          }).then(res => {
            this.$message.success('新增成功')
            this.handleClose()
            this.listData()
          });
        }
      });
    },
    handleClose() {
      this.form = {
        id: undefined,
        name: undefined,
        menuIds: []
      };
      this.$refs['saveOrUpdateForm'].resetFields()
      this.$refs.menuTree.setCheckedKeys([])
      this.dialogVisible = false
    },
  },
  mounted() {
    this.listData()
  }
}
</script>